import '../prompt/prompt.css'
import Prompt from '../prompt/prompt.js'
import BasePlot from './basePlot';
import util from '../util';
/**
 * 扇环标绘工具类（支持编辑版）
 * 提供交互式扇环标绘功能，支持鼠标绘制、参数调整、样式配置及编辑操作
 */
class SectorRingDrawer extends BasePlot {
  constructor(viewer, style) {
    super(viewer, style);
    this.type = "sectorRing";
    this.viewer = viewer;
    this.style = style;

    // 初始化中心点、边缘点、角度点等属性
    this.center = null;
    this.innerRadius = style.innerRadius || 500;
    this.outerRadius = style.outerRadius || 2000;
    // 角度初始化时直接使用角度值，createSectorRing方法中会转换为弧度
    this.startAngle = Cesium.Math.toRadians(style.startAngle || 0);
    this.endAngle = Cesium.Math.toRadians(style.endAngle || 90);
    this.entity = null;
    // 标记扇环是否可编辑，默认为true，除非显式设置为false
    this.isEditable = style.canEdit !== undefined ? style.canEdit : true;

    // 样式配置（合并默认与用户配置）
    this.style = {
      material: Cesium.Color.RED.withAlpha(0.5),
      outline: true,
      outlineColor: Cesium.Color.YELLOW,
      outlineWidth: 3,
      handleSize: 10,         // 编辑控制点大小
      handleColor: Cesium.Color.BLUE,
      ...style
    };

    // 调试模式
    this.debugMode = true;
  }

  /**
   * 检查 Cartesian3 对象是否包含 NaN 分量
   * @param {Cesium.Cartesian3} cartesian 
   * @returns {Boolean}
   */
  hasNaNComponent(cartesian) {
    return isNaN(cartesian.x) || isNaN(cartesian.y) || isNaN(cartesian.z);
  }

  /**
   * 开始标绘扇环
   * @param {Function} callback 标绘完成回调函数
   */
  start(callback) {
    if (!this.prompt && this.promptStyle.show) {
      this.prompt = new Prompt(this.viewer, this.promptStyle);
    }
    this.state = "startCreate";
    this.isDrawing = true;
    this.isSettingInnerRadius = false;
    this.isSettingOuterRadius = false;
    this.isSettingStartAngle = false;
    this.isSettingEndAngle = false;
    const that = this;

    // 初始化绘制事件处理器
    if (!this.handler) {
      this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
    }

    // 左键按下事件 - 开始设置内半径、外半径或角度
    this.handler.setInputAction(function (evt) {
      that.lastMousePosition = evt.position;
      const cartesian = that.getCatesian3FromPX(evt.position);

      // 检查是否获得有效坐标
      if (!cartesian || that.hasNaNComponent(cartesian)) {
        console.warn('无效坐标，忽略操作');
        return;
      }

      if (!that.centerPoint) {
        // 第一点：中心点
        that.center = cartesian;
        that.centerPoint = that.createPoint(cartesian);
        that.centerPoint.typeAttr = "center";

        // 初始化内半径和外半径控制点
        that.innerStartPoint = that.createPoint(cartesian.clone());
        that.innerStartPoint.typeAttr = "innerStart";
        that.outerStartPoint = that.createPoint(cartesian.clone());
        that.outerStartPoint.typeAttr = "outerStart";
        that.outerEndPoint = that.createPoint(cartesian.clone());
        that.outerEndPoint.typeAttr = "outerEnd";

        that.centerPoint.show = true
        that.innerStartPoint.show = true
        that.outerStartPoint.show = true
        that.outerEndPoint.show = true


        that.isSettingInnerRadius = true;
        that.prompt.update(evt.position, "拖动鼠标调整内半径，松开左键确认");
      } else if (that.isSettingInnerRadius) {
        // 结束设置内半径
        that.isSettingInnerRadius = false;
        that.innerStartPoint.position.setValue(cartesian);
        that.innerRadius = Cesium.Cartesian3.distance(that.center, cartesian);

        // 计算起始角度（相对于正北方向）
        const heading = that.calculateHeading(that.center, cartesian);
        that.startAngle = heading;
        that.endAngle = heading; // 初始结束角度与起始角度相同

        // 更新控制点位置
        const innerStartPos = that.getPositionByAngleAndRadius(that.startAngle, that.innerRadius);
        const outerStartPos = that.getPositionByAngleAndRadius(that.startAngle, that.outerRadius);
        const outerEndPos = that.getPositionByAngleAndRadius(that.endAngle, that.outerRadius);
        that.innerStartPoint.position.setValue(innerStartPos);
        that.outerStartPoint.position.setValue(outerStartPos);
        that.outerEndPoint.position.setValue(outerEndPos);

        // 创建扇环实体
        if (that.entity) {
          that.viewer.entities.remove(that.entity);
        }
        that.entity = that.createSectorRing(
          that.center,
          that.innerRadius,
          that.outerRadius,
          that.startAngle,
          that.endAngle
        );

        that.isSettingOuterRadius = true;
        that.prompt.update(evt.position, "拖动鼠标调整外半径，松开左键确认");
      } else if (that.isSettingOuterRadius) {
        // 结束设置外半径
        that.isSettingOuterRadius = false;
        that.outerStartPoint.position.setValue(cartesian);
        that.outerRadius = Cesium.Cartesian3.distance(that.center, cartesian);

        // 更新控制点位置
        const innerStartPos = that.getPositionByAngleAndRadius(that.startAngle, that.innerRadius);
        const outerStartPos = that.getPositionByAngleAndRadius(that.startAngle, that.outerRadius);
        const outerEndPos = that.getPositionByAngleAndRadius(that.endAngle, that.outerRadius);
        that.innerStartPoint.position.setValue(innerStartPos);
        that.outerStartPoint.position.setValue(outerStartPos);
        that.outerEndPoint.position.setValue(outerEndPos);

        // 更新扇环实体
        if (that.entity) {
          that.viewer.entities.remove(that.entity);
        }
        that.entity = that.createSectorRing(
          that.center,
          that.innerRadius,
          that.outerRadius,
          that.startAngle,
          that.endAngle
        );

        that.isSettingStartAngle = true;
        that.prompt.update(evt.position, "拖动鼠标调整起始角度，松开左键确认");
      } else if (that.isSettingStartAngle) {
        // 结束设置起始角度
        that.isSettingStartAngle = false;
        that.innerStartPoint.position.setValue(cartesian);
        that.outerStartPoint.position.setValue(cartesian);

        // 计算起始角度
        const heading = that.calculateHeading(that.center, cartesian);
        that.startAngle = heading;

        // 确保角度范围在0-2π之间
        if (that.startAngle < 0) {
          that.startAngle += Cesium.Math.TWO_PI;
        }

        // 更新控制点位置
        const innerStartPos = that.getPositionByAngleAndRadius(that.startAngle, that.innerRadius);
        const outerStartPos = that.getPositionByAngleAndRadius(that.startAngle, that.outerRadius);
        const outerEndPos = that.getPositionByAngleAndRadius(that.endAngle, that.outerRadius);
        that.innerStartPoint.position.setValue(innerStartPos);
        that.outerStartPoint.position.setValue(outerStartPos);
        that.outerEndPoint.position.setValue(outerEndPos);

        // 更新扇环实体
        if (that.entity) {
          that.viewer.entities.remove(that.entity);
        }
        that.entity = that.createSectorRing(
          that.center,
          that.innerRadius,
          that.outerRadius,
          that.startAngle,
          that.endAngle
        );

        that.isSettingEndAngle = true;
        that.prompt.update(evt.position, "拖动鼠标调整结束角度，松开左键确认");
      } else if (that.isSettingEndAngle) {
        // 结束设置结束角度
        that.isSettingEndAngle = false;
        that.outerEndPoint.position.setValue(cartesian);

        // 计算结束角度
        const heading = that.calculateHeading(that.center, cartesian);
        that.endAngle = heading;

        // 确保角度范围在0-2π之间
        if (that.endAngle < 0) {
          that.endAngle += Cesium.Math.TWO_PI;
        }

        // 确保结束角度大于起始角度
        if (that.endAngle < that.startAngle) {
          that.endAngle += Cesium.Math.TWO_PI;
        }

        // 更新控制点位置
        const innerStartPos = that.getPositionByAngleAndRadius(that.startAngle, that.innerRadius);
        const outerStartPos = that.getPositionByAngleAndRadius(that.startAngle, that.outerRadius);
        const outerEndPos = that.getPositionByAngleAndRadius(that.endAngle, that.outerRadius);
        that.innerStartPoint.position.setValue(innerStartPos);
        that.outerStartPoint.position.setValue(outerStartPos);
        that.outerEndPoint.position.setValue(outerEndPos);

        // 更新扇环实体
        if (that.entity) {
          that.viewer.entities.remove(that.entity);
        }
        that.entity = that.createSectorRing(
          that.center,
          that.innerRadius,
          that.outerRadius,
          that.startAngle,
          that.endAngle
        );

        // 标绘完成，隐藏控制点和提示
        that.endCreate();
        if (callback) callback(that.entity);

        // 启用扇环点击编辑功能
        that.enableClickToEdit();
      }
    }, Cesium.ScreenSpaceEventType.LEFT_DOWN);

    // 鼠标移动事件 - 动态绘制
    this.handler.setInputAction(function (evt) {
      that.lastMousePosition = evt.endPosition;
      const cartesian = that.getCatesian3FromPX(evt.endPosition);

      // 检查是否获得有效坐标
      if (!cartesian || that.hasNaNComponent(cartesian)) {
        return;
      }

      if (!that.centerPoint) {
        that.prompt.update(evt.endPosition, "单击确定扇环中心点");
      } else if (that.isSettingInnerRadius) {
        // 正在调整内半径
        that.prompt.update(evt.endPosition, "拖动鼠标调整内半径，松开左键确认");
        that.innerStartPoint.position.setValue(cartesian);
        that.innerRadius = Cesium.Cartesian3.distance(that.center, cartesian);

        // 更新控制点位置
        const innerStartPos = that.getPositionByAngleAndRadius(that.startAngle, that.innerRadius);
        const outerStartPos = that.getPositionByAngleAndRadius(that.startAngle, that.outerRadius);
        const outerEndPos = that.getPositionByAngleAndRadius(that.endAngle, that.outerRadius);
        that.innerStartPoint.position.setValue(innerStartPos);
        that.outerStartPoint.position.setValue(outerStartPos);
        that.outerEndPoint.position.setValue(outerEndPos);

        // 更新扇环显示
        if (that.entity) {
          that.viewer.entities.remove(that.entity);
          that.entity = that.createSectorRing(
            that.center,
            that.innerRadius,
            that.outerRadius,
            that.startAngle,
            that.endAngle
          );
        }
      } else if (that.isSettingOuterRadius) {
        // 正在调整外半径
        that.prompt.update(evt.endPosition, "拖动鼠标调整外半径，松开左键确认");
        that.outerStartPoint.position.setValue(cartesian);
        that.outerRadius = Cesium.Cartesian3.distance(that.center, cartesian);

        // 更新控制点位置
        const innerStartPos = that.getPositionByAngleAndRadius(that.startAngle, that.innerRadius);
        const outerStartPos = that.getPositionByAngleAndRadius(that.startAngle, that.outerRadius);
        const outerEndPos = that.getPositionByAngleAndRadius(that.endAngle, that.outerRadius);
        that.innerStartPoint.position.setValue(innerStartPos);
        that.outerStartPoint.position.setValue(outerStartPos);
        that.outerEndPoint.position.setValue(outerEndPos);

        // 更新扇环显示
        if (that.entity) {
          that.viewer.entities.remove(that.entity);
        }
        that.entity = that.createSectorRing(
          that.center,
          that.innerRadius,
          that.outerRadius,
          that.startAngle,
          that.endAngle
        );
      } else if (that.isSettingStartAngle) {
        // 正在调整起始角度
        that.prompt.update(evt.endPosition, "拖动鼠标调整起始角度，松开左键确认");
        that.innerStartPoint.position.setValue(cartesian);
        that.outerStartPoint.position.setValue(cartesian);

        // 计算起始角度
        const heading = that.calculateHeading(that.center, cartesian);
        that.startAngle = heading;

        // 确保角度范围在0-2π之间
        if (that.startAngle < 0) {
          that.startAngle += Cesium.Math.TWO_PI;
        }

        // 更新控制点位置
        const innerStartPos = that.getPositionByAngleAndRadius(that.startAngle, that.innerRadius);
        const outerStartPos = that.getPositionByAngleAndRadius(that.startAngle, that.outerRadius);
        const outerEndPos = that.getPositionByAngleAndRadius(that.endAngle, that.outerRadius);
        that.innerStartPoint.position.setValue(innerStartPos);
        that.outerStartPoint.position.setValue(outerStartPos);
        that.outerEndPoint.position.setValue(outerEndPos);

        // 更新扇环显示
        if (that.entity) {
          that.viewer.entities.remove(that.entity);
        }
        that.entity = that.createSectorRing(
          that.center,
          that.innerRadius,
          that.outerRadius,
          that.startAngle,
          that.endAngle
        );
      } else if (that.isSettingEndAngle) {
        // 正在调整结束角度
        that.prompt.update(evt.endPosition, "拖动鼠标调整结束角度，松开左键确认");
        that.outerEndPoint.position.setValue(cartesian);

        // 计算结束角度
        const heading = that.calculateHeading(that.center, cartesian);
        that.endAngle = heading;

        // 确保角度范围在0-2π之间
        if (that.endAngle < 0) {
          that.endAngle += Cesium.Math.TWO_PI;
        }

        // 确保结束角度大于起始角度
        if (that.endAngle < that.startAngle) {
          that.endAngle += Cesium.Math.TWO_PI;
        }

        // 更新控制点位置
        const innerStartPos = that.getPositionByAngleAndRadius(that.startAngle, that.innerRadius);
        const outerStartPos = that.getPositionByAngleAndRadius(that.startAngle, that.outerRadius);
        const outerEndPos = that.getPositionByAngleAndRadius(that.endAngle, that.outerRadius);
        that.innerStartPoint.position.setValue(innerStartPos);
        that.outerStartPoint.position.setValue(outerStartPos);
        that.outerEndPoint.position.setValue(outerEndPos);

        // 更新扇环显示
        if (that.entity) {
          that.viewer.entities.remove(that.entity);
        }
        that.entity = that.createSectorRing(
          that.center,
          that.innerRadius,
          that.outerRadius,
          that.startAngle,
          that.endAngle
        );
      }

    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
  }

  /**
   * 内部方法：创建扇环实体
   * @param {Cesium.Cartesian3} center 中心点
   * @param {Number} innerRadius 内半径
   * @param {Number} outerRadius 外半径
   * @param {Number} startAngle 起始角度
   * @param {Number} endAngle 结束角度
   * @returns {Cesium.Entity} 扇环实体
   */
  createSectorRing(center, innerRadius, outerRadius, startAngle, endAngle) {
    if (this.debugMode) {
      console.log('[SectorRingDrawer] Creating sector ring with parameters:', {
        center, innerRadius, outerRadius, startAngle, endAngle
      });
    }

    // 角度已经以弧度存储
    const startRad = startAngle;
    const endRad = endAngle;
    const angleDiff = endRad - startRad;

    // 计算顶点（按1°间隔采样，保证平滑度）
    const points = [];
    const sampleCount = Math.ceil(angleDiff / Cesium.Math.toRadians(1)) + 1;

    // 获取中心点的高度
    const centerCartographic = Cesium.Cartographic.fromCartesian(center);
    const centerHeight = centerCartographic.height;

    if (isNaN(centerHeight)) {
      console.error('[SectorRingDrawer] Invalid height from center point:', center);
      // 尝试使用默认高度
      return this.createSectorRingWithDefaultHeight(center, innerRadius, outerRadius, startAngle, endAngle);
    }

    // 外圆弧顶点（从结束角度到起始角度，顺时针）
    for (let i = 0; i <= sampleCount; i++) {
      const angle = endRad - (i * angleDiff) / sampleCount;
      const offset = this.calculateOffset(angle, outerRadius, centerCartographic);
      const position = Cesium.Cartesian3.add(center, offset, new Cesium.Cartesian3());
      const cartographic = Cesium.Cartographic.fromCartesian(position);
      cartographic.height = centerHeight;
      points.push(cartographic);
    }

    // 内圆弧顶点（从起始角度到结束角度，逆时针，闭合多边形）
    for (let i = 0; i <= sampleCount; i++) {
      const angle = startRad + (i * angleDiff) / sampleCount;
      const offset = this.calculateOffset(angle, innerRadius, centerCartographic);
      const position = Cesium.Cartesian3.add(center, offset, new Cesium.Cartesian3());
      const cartographic = Cesium.Cartographic.fromCartesian(position);
      cartographic.height = centerHeight;
      points.push(cartographic);
    }

    // 创建多边形层级
    const polygonHierarchy = new Cesium.PolygonHierarchy(
      points.map(p => Cesium.Cartesian3.fromRadians(p.longitude, p.latitude, p.height))
    );

    if (this.debugMode) {
      // console.log('[SectorRingDrawer] Created polygon hierarchy with',
      //   polygonHierarchy.positions.length, 'vertices');
    }

    // 创建并返回实体
    const entity = this.viewer.entities.add({
      polygon: {
        hierarchy: polygonHierarchy,
        material: this.style.material,
        outline: this.style.outline,
        outlineColor: this.style.outlineColor,
        outlineWidth: this.style.outlineWidth,
        perPositionHeight: true,
        classificationType: Cesium.ClassificationType.BOTH
      },
      description: `扇环: 内半径=${innerRadius}m, 外半径=${outerRadius}m, 角度=${Cesium.Math.toDegrees(startAngle)}°-${Cesium.Math.toDegrees(endAngle)}°`
    });

    if (this.debugMode && entity) {
      // console.log('[SectorRingDrawer] Successfully created entity with ID:', entity.id);
    }

    return entity;
  }

  /**
   * 内部方法：使用默认高度创建扇环实体（当无法获取有效高度时）
   */
  createSectorRingWithDefaultHeight(center, innerRadius, outerRadius, startAngle, endAngle) {
    console.log('[SectorRingDrawer] Using default height (10m) for sector ring');

    // 创建一个基于中心位置的新Cartesian3，但高度设为10米
    const centerCartographic = Cesium.Cartographic.fromCartesian(center);
    centerCartographic.height = 10;
    const newCenter = Cesium.Cartesian3.fromRadians(
      centerCartographic.longitude,
      centerCartographic.latitude,
      centerCartographic.height
    );

    return this.createSectorRing(newCenter, innerRadius, outerRadius, startAngle, endAngle);
  }

  /**
   * 内部方法：计算基于角度和距离的偏移量，考虑地形朝向
   */
  calculateOffset(angle, distance, centerCartographic) {
    // 计算偏移量，考虑地形的朝向（法线方向）
    const normal = Cesium.Ellipsoid.WGS84.geodeticSurfaceNormal(
      Cesium.Cartesian3.fromRadians(
        centerCartographic.longitude,
        centerCartographic.latitude,
        centerCartographic.height
      )
    );

    // 创建局部坐标系
    const east = Cesium.Cartesian3.cross(
      new Cesium.Cartesian3(0, 0, 1),
      normal,
      new Cesium.Cartesian3()
    );
    Cesium.Cartesian3.normalize(east, east);

    const north = Cesium.Cartesian3.cross(normal, east, new Cesium.Cartesian3());

    // 计算基于角度的偏移
    const x = Math.cos(angle) * distance;
    const y = Math.sin(angle) * distance;

    // 组合偏移
    const offset = new Cesium.Cartesian3();
    Cesium.Cartesian3.multiplyByScalar(east, y, offset);
    const temp = new Cesium.Cartesian3();
    Cesium.Cartesian3.multiplyByScalar(north, x, temp);
    Cesium.Cartesian3.add(offset, temp, offset);

    return offset;
  }

  /**
   * 内部方法：计算从中心点到目标点的角度
   */
  calculateHeading(center, point) {
    const centerCartographic = Cesium.Cartographic.fromCartesian(center);
    const pointCartographic = Cesium.Cartographic.fromCartesian(point);

    // 计算经度和纬度的差值
    const deltaLongitude = pointCartographic.longitude - centerCartographic.longitude;
    const deltaLatitude = pointCartographic.latitude - centerCartographic.latitude;

    // 使用atan2计算角度
    let heading = Math.atan2(deltaLongitude, deltaLatitude);

    // 将角度转换为0到2π范围内
    if (heading < 0) {
      heading += Cesium.Math.TWO_PI;
    }

    return heading;
  }

  /**
   * 内部方法：计算三点形成的角度
   * @param {Cesium.Cartesian3} point1 第一个点
   * @param {Cesium.Cartesian3} point2 第二个点
   * @param {Cesium.Cartesian3} center 中心点
   * @returns {Number} 角度（弧度）
   */
  calculateAngle(point1, point2, center) {
    // 计算从中心点到两个点的向量
    const vector1 = Cesium.Cartesian3.subtract(point1, center, new Cesium.Cartesian3());
    const vector2 = Cesium.Cartesian3.subtract(point2, center, new Cesium.Cartesian3());

    // 归一化向量
    Cesium.Cartesian3.normalize(vector1, vector1);
    Cesium.Cartesian3.normalize(vector2, vector2);

    // 计算向量点积
    const dotProduct = Cesium.Cartesian3.dot(vector1, vector2);

    // 确保点积在有效范围内（-1到1）
    const clampedDotProduct = Math.max(-1.0, Math.min(1.0, dotProduct));

    // 计算角度（弧度）
    let angle = Math.acos(clampedDotProduct);

    // 确保角度在0到2π范围内
    if (angle < 0) {
      angle += Cesium.Math.TWO_PI;
    }

    return angle;
  }

  /**
   * 禁用扇环点击编辑功能
   */
  disableClickToEdit() {
    if (this.clickHandler) {
      this.clickHandler.destroy();
      this.clickHandler = null;
    }

    this.isEditable = false;
  }

  /**
   * 启用扇环点击编辑功能
   */
  enableClickToEdit() {
    // 先禁用现有点击处理器
    this.disableClickToEdit();

    this.clickHandler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
    const that = this;

    // 左键点击事件
    this.clickHandler.setInputAction(function (evt) {
      const pick = that.viewer.scene.pick(evt.position);
      if (Cesium.defined(pick) && pick.id === that.entity) {
        // 不允许在editing和startEdit状态下再次点击编辑
        if (that.state === "editing" || that.state === "startEdit") {
          return; // 正在编辑中或正在开始编辑，不处理点击事件
        }
        console.log('Clicked on sector ring, starting edit...'); // 调试输出
        if (that.entity) {
          // 创建自定义事件并传递实体数据
          console.log(that.entity)
          const event = new CustomEvent('sh-start', {
            detail: {
              entityObj: that,
              entity: that.entity
            }
          });
          window.dispatchEvent(event);
        }
        // 点击了当前扇环，开始编辑
        that.startEdit();
      } else if (that.state === "editing" || that.state === "startEdit") {
        console.log('4', that.start)
        // 排除endCreate状态，仅在editing或startEdit状态下点击非扇环区域才结束编辑
        if (that.state !== "endCreate") {
          that.endEdit();
          console.log('3')
        }
      }
      console.log('2')
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

    this.isEditable = true;
  }

  /**
   * 开始编辑扇环
   */
  startEdit() {
    // 移除对isEditable的检查，始终允许编辑
    // if (!this.isEditable) {
    //   console.warn('扇环不可编辑');
    //   return;
    // }

    this.state = "editing";
    this.editHandler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
    this.createEditHandles(); // 创建编辑控制点
    
    // 确保控制点可见
    if (this.editHandles) {
      Object.values(this.editHandles).forEach(handle => {
        if (handle && handle.point) {
          handle.point.show = true;
        }
      });
    }
    
    const that = this;

    // 鼠标悬浮事件 - 拾取控制点
    this.editHandler.setInputAction(function (evt) {
      if (that.state !== "editing") return;

      const pick = that.viewer.scene.pick(evt.endPosition);
      if (Cesium.defined(pick) && pick.id && pick.id.isEditPoint) {
        that.viewer.scene.canvas.style.cursor = 'pointer';
      } else {
        that.viewer.scene.canvas.style.cursor = 'default';
      }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    // 左键按下事件 - 拾取控制点
    this.editHandler.setInputAction(function (evt) {
      if (that.state !== "editing") return;

      const pick = that.viewer.scene.pick(evt.position);
      if (Cesium.defined(pick) && pick.id && pick.id.isEditPoint) {
        that.draggingPoint = pick.id;
        that.viewer.scene.screenSpaceCameraController.enableRotate = false;
      }
    }, Cesium.ScreenSpaceEventType.LEFT_DOWN);

    // 鼠标移动事件 - 拖动控制点
    this.editHandler.setInputAction(function (evt) {
      if (that.state !== "editing" || !that.draggingPoint) return;

      const cartesian = that.getCatesian3FromPX(evt.endPosition);
      if (!cartesian || that.hasNaNComponent(cartesian)) return;

      // 更新控制点位置
      that.draggingPoint.position.setValue(cartesian);

      // 根据拖动的控制点类型更新扇环参数
      const pointType = that.draggingPoint.pointType;
      switch (pointType) {
        case 'center':
          // 计算中心点的偏移量
          const oldCenter = that.center;
          that.center = cartesian;
          const offset = Cesium.Cartesian3.subtract(cartesian, oldCenter, new Cesium.Cartesian3());

          // 更新其他编辑点的位置
          if (that.editHandles) {
            // 更新内半径控制点
            const innerStartPos = that.editHandles.innerStart.position.getValue(Cesium.JulianDate.now());
            const newInnerStartPos = Cesium.Cartesian3.add(innerStartPos, offset, new Cesium.Cartesian3());
            that.editHandles.innerStart.position.setValue(newInnerStartPos);

            // 更新外半径控制点
            const outerStartPos = that.editHandles.outerStart.position.getValue(Cesium.JulianDate.now());
            const newOuterStartPos = Cesium.Cartesian3.add(outerStartPos, offset, new Cesium.Cartesian3());
            that.editHandles.outerStart.position.setValue(newOuterStartPos);

            // 更新外半径结束控制点
            const outerEndPos = that.editHandles.outerEnd.position.getValue(Cesium.JulianDate.now());
            const newOuterEndPos = Cesium.Cartesian3.add(outerEndPos, offset, new Cesium.Cartesian3());
            that.editHandles.outerEnd.position.setValue(newOuterEndPos);
          }
          break;
        case 'innerRadius':
          that.innerRadius = Cesium.Cartesian3.distance(that.center, cartesian);
          break;
        case 'outerRadius':
          that.outerRadius = Cesium.Cartesian3.distance(that.center, cartesian);
          break;
        case 'startAngle':
          // 计算起始角度
          const startHeading = that.calculateHeading(that.center, cartesian);
          that.startAngle = startHeading;

          // 确保角度在0到2π范围内
          if (that.startAngle < 0) {
            that.startAngle += Cesium.Math.TWO_PI;
          }
          break;
        case 'endAngle':
          // 计算结束角度
          const endHeading = that.calculateHeading(that.center, cartesian);
          that.endAngle = endHeading;

          // 确保角度在0到2π范围内
          if (that.endAngle < 0) {
            that.endAngle += Cesium.Math.TWO_PI;
          }

          // 确保结束角度大于起始角度
          if (that.endAngle < that.startAngle) {
            that.endAngle += Cesium.Math.TWO_PI;
          }
          break;
      }
      // 更新扇环实体
      that.entity = that.createSectorRingEntity();
      if (that.entity) {
        // 创建自定义事件并传递实体数据
        const event = new CustomEvent('sh-editing', {
          detail: {
            entityObj: that,
            entity: that.entity
          }
        });
        window.dispatchEvent(event);
      }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    // 左键释放事件 - 结束拖动
    this.editHandler.setInputAction(function (evt) {
      if (that.state !== "editing" || !that.draggingPoint) return;

      that.draggingPoint = null;
      that.viewer.scene.screenSpaceCameraController.enableRotate = true;
    }, Cesium.ScreenSpaceEventType.LEFT_UP);
  }

  /**
   * 获取当前样式配置
   * @returns {Object} 样式配置
   */
  getStyle() {
    if (!this.entity) return {};
    const polygon = this.entity.polygon;
    const color = polygon.material.color.getValue();
    const outlineColor = polygon.outlineColor.getValue();
    let colorStr = new Cesium.Color(
      color.red,
      color.green,
      color.blue,
      1
    ).toCssHexString();

    return {
      color: colorStr,
      colorAlpha: color.alpha,
      outline: polygon.outline.getValue(),
      outlineColor: Cesium.Color.fromRgba(outlineColor).toCssHexString(),
      outlineWidth: polygon.outlineWidth._value,
      // heightReference: polygon.heightReference.getValue()
    };
  }
  setStyle(style) {
    if (!style || !this.entity) return;
    const polygon = this.entity.polygon;

    if (style.color) {
      const color = Cesium.Color.fromCssColorString(style.color)
        .withAlpha(style.colorAlpha !== undefined ? style.colorAlpha : 0.5);
      polygon.material = color;
    }

    if (style.outline !== undefined) polygon.outline = style.outline;
    if (style.outlineColor) {
      polygon.outlineColor = Cesium.Color.fromCssColorString(style.outlineColor);
    }
    if (style.outlineWidth) polygon.outlineWidth = style.outlineWidth;
    if (style.heightReference !== undefined) {
      polygon.heightReference = style.heightReference;
    }

    this.style = { ...this.style, ...style };
  }

  /**
   * 内部方法：创建编辑控制点
   */
  createEditHandles() {
    const handles = {};

    // 中心点控制柄（蓝色）
    handles.center = this.viewer.entities.add({
      position: this.center,
      point: {
        pixelSize: this.style.handleSize,
        color: this.style.handleColor,
        outlineColor: Cesium.Color.WHITE,
        outlineWidth: 2
      },
      isEditPoint: true, // 标记为编辑点
      pointType: 'center' // 标记点类型
    });

    // 内半径控制柄（绿色）
    const innerStartPos = this.getPositionByAngleAndRadius(
      this.startAngle,
      this.innerRadius
    );
    handles.innerStart = this.viewer.entities.add({
      position: innerStartPos,
      point: {
        pixelSize: this.style.handleSize,
        color: Cesium.Color.LIME,
        outlineColor: Cesium.Color.WHITE,
        outlineWidth: 2
      },
      isEditPoint: true, // 标记为编辑点
      pointType: 'innerRadius' // 标记点类型
    });

    // 外半径控制柄（绿色）
    const outerStartPos = this.getPositionByAngleAndRadius(
      this.startAngle,
      this.outerRadius
    );
    handles.outerStart = this.viewer.entities.add({
      position: outerStartPos,
      point: {
        pixelSize: this.style.handleSize,
        color: Cesium.Color.LIME,
        outlineColor: Cesium.Color.WHITE,
        outlineWidth: 2
      },
      isEditPoint: true, // 标记为编辑点
      pointType: 'outerRadius' // 标记点类型
    });

    // 外半径结束控制柄（青色）
    const outerEndPos = this.getPositionByAngleAndRadius(
      this.endAngle,
      this.outerRadius
    );
    handles.outerEnd = this.viewer.entities.add({
      position: outerEndPos,
      point: {
        pixelSize: this.style.handleSize,
        color: Cesium.Color.CYAN,
        outlineColor: Cesium.Color.WHITE,
        outlineWidth: 2
      },
      isEditPoint: true, // 标记为编辑点
      pointType: 'endAngle' // 标记点类型
    });

    this.editHandles = handles;
  }

  /**
   * 内部方法：根据角度和半径计算位置
   */
  getPositionByAngleAndRadius(angle, radius) {
    const centerCartographic = Cesium.Cartographic.fromCartesian(this.center);
    const offset = this.calculateOffset(
      angle,
      radius,
      centerCartographic
    );
    return Cesium.Cartesian3.add(this.center, offset, new Cesium.Cartesian3());
  }

  /**
   * 内部方法：更新扇环实体
   */
  updateSectorRing() {
    const center = this.center;
    const innerStartPos = this.editHandles.innerStart.position.getValue(Cesium.JulianDate.now());
    const outerStartPos = this.editHandles.outerStart.position.getValue(Cesium.JulianDate.now());
    const outerEndPos = this.editHandles.outerEnd.position.getValue(Cesium.JulianDate.now());

    this.innerRadius = Cesium.Cartesian3.distance(center, innerStartPos);
    this.outerRadius = Cesium.Cartesian3.distance(center, outerStartPos);

    // 计算起始角度和结束角度
    let startHeading = this.calculateHeading(center, outerStartPos);
    let endHeading = this.calculateHeading(center, outerEndPos);

    // 确保角度在0到2π范围内
    if (startHeading < 0) startHeading += Cesium.Math.TWO_PI;
    if (endHeading < 0) endHeading += Cesium.Math.TWO_PI;

    this.startAngle = startHeading;
    this.endAngle = endHeading;

    // 确保结束角度大于起始角度
    if (this.endAngle < this.startAngle) {
      this.endAngle += Cesium.Math.TWO_PI;
    }

    if (this.entity) {
      this.viewer.entities.remove(this.entity);
    }

    this.entity = this.createSectorRing(
      center,
      this.innerRadius,
      this.outerRadius,
      this.startAngle,
      this.endAngle
    );
  }

  /**
   * 结束编辑扇环
   */
  endEdit() {
    // 销毁编辑控制点
    if (this.editHandles) {
      Object.values(this.editHandles).forEach(handle => {
        if (handle) {
          this.viewer.entities.remove(handle);
        }
      });
      this.editHandles = null;
    }

    // 销毁编辑事件处理器
    if (this.editHandler) {
      this.editHandler.destroy();
      this.editHandler = null;
    }

    this.viewer.scene.canvas.style.cursor = 'default';
    this.viewer.scene.screenSpaceCameraController.enableRotate = true;
    this.state = "endEdit";

    // 重新启用点击编辑功能
    this.enableClickToEdit();

    if (this.entity) {
      // 创建自定义事件并传递实体数据
      const event = new CustomEvent('sh-end', {
        detail: {
          entityObj: this,
          entity: this.entity
        }
      });
      window.dispatchEvent(event);
    }
  }
  endCreate() {

    const that = this;
    if (that.handler) {
      that.handler.destroy();
      that.handler = null;
    }
    // 隐藏控制点（编辑时再显示）
    if (that.centerPoint) that.centerPoint.show = false;
    if (that.innerStartPoint) that.innerStartPoint.show = false;
    if (that.outerStartPoint) that.outerStartPoint.show = false;
    if (that.outerEndPoint) that.outerEndPoint.show = false;
    if (that.prompt) {
      that.prompt.destroy();
      that.prompt = null;
    }
    that.state = "endCreate";
    that.isDrawing = false;
    that.isSettingInnerRadius = false;
    that.isSettingOuterRadius = false;
    that.isSettingStartAngle = false;
    that.isSettingEndAngle = false;

    // 添加objId属性，用于标识实体
    if (that.entity) {
      that.entity.objId = Date.now();
      that.entity.type = "sectorRing"; // 添加类型标识
    }

    // 启用扇环点击编辑功能
    this.enableClickToEdit();
  }

  /**
   * 创建扇环实体（类似createSector方法）
   * @returns {Cesium.Entity} 扇环实体
   */
  createSectorRingEntity() {
    // 移除旧实体
    if (this.entity) {
      this.viewer.entities.remove(this.entity);
    }

    // 检查是否有有效的中心点和半径
    if (!this.center || this.hasNaNComponent(this.center) || this.innerRadius <= 0 || this.outerRadius <= 0) {
      return null;
    }

    const that = this;
    // 创建扇环面实体
    const entity = this.viewer.entities.add({
      polygon: {
        hierarchy: new Cesium.CallbackProperty(function () {
          // 动态计算扇环顶点
          return new Cesium.PolygonHierarchy(that.generateSectorRingPositions());
        }, false),
        height: 0,
        heightReference: this.style.heightReference || Cesium.HeightReference.NONE,
        fill: this.style.fill !== undefined ? this.style.fill : true,
        material: this.style.color
          ? (typeof this.style.color === 'string'
            ? Cesium.Color.fromCssColorString(this.style.color).withAlpha(this.style.colorAlpha || 0.5)
            : this.style.color)
          : Cesium.Color.RED.withAlpha(0.5),
        outline: this.style.outline !== undefined ? this.style.outline : true,
        outlineColor: this.style.outlineColor
          ? (typeof this.style.outlineColor === 'string'
            ? Cesium.Color.fromCssColorString(this.style.outlineColor)
            : this.style.outlineColor)
          : Cesium.Color.BLACK,
        outlineWidth: this.style.outlineWidth || 1,
        disableDepthTestDistance: Number.POSITIVE_INFINITY
      }
    });

    // 恢复实体的标识属性
    if (this.entity && this.entity.objId) {
      entity.objId = this.entity.objId;
      entity.type = "sectorRing";
    }

    return entity;
  }

  /**
   * 生成扇环的顶点坐标
   * @returns {Array<Cesium.Cartesian3>} 顶点坐标数组
   */
  generateSectorRingPositions() {
    // 检查输入是否有效
    if (!this.center || this.hasNaNComponent(this.center) || this.innerRadius <= 0 || this.outerRadius <= 0) {
      return [];
    }

    const positions = [];

    // 确保角度范围正确
    let startAngle = this.startAngle;
    let endAngle = this.endAngle;
    if (startAngle > endAngle) {
      const temp = startAngle;
      startAngle = endAngle;
      endAngle = temp;
    }

    // 角度步长（控制扇环平滑度）
    const step = 0.05;
    const numPoints = Math.ceil((endAngle - startAngle) / step);

    // 生成外圆弧边缘点
    for (let i = 0; i <= numPoints; i++) {
      const angle = startAngle + i * step;
      const position = this.getPositionByAngleAndRadius(angle, this.outerRadius);
      // 检查生成的坐标是否有效
      if (!this.hasNaNComponent(position)) {
        positions.push(position);
      }
    }

    // 生成内圆弧边缘点（逆序添加以形成闭合环）
    for (let i = numPoints; i >= 0; i--) {
      const angle = startAngle + i * step;
      const position = this.getPositionByAngleAndRadius(angle, this.innerRadius);
      // 检查生成的坐标是否有效
      if (!this.hasNaNComponent(position)) {
        positions.push(position);
      }
    }

    // 闭合扇环
    if (positions.length > 0) {
      positions.push(positions[0]);
    }

    return positions;
  }

  /**
   * 销毁扇环标绘
   */
  destroy() {
    this.disableClickToEdit();

    if (this.entity) {
      this.viewer.entities.remove(this.entity);
    }
    if (this.centerPoint) {
      this.viewer.entities.remove(this.centerPoint);
    }
    if (this.innerStartPoint) {
      this.viewer.entities.remove(this.innerStartPoint);
    }
    if (this.outerStartPoint) {
      this.viewer.entities.remove(this.outerStartPoint);
    }
    if (this.outerEndPoint) {
      this.viewer.entities.remove(this.outerEndPoint);
    }
    if (this.handler) {
      this.handler.destroy();
      this.handler = null;
    }
    if (this.prompt) {
      this.prompt.destroy();
      this.prompt = null;
    }
    this.state = null;
    this.isDrawing = false;
    this.isSettingInnerRadius = false;
    this.isSettingOuterRadius = false;
    this.isSettingStartAngle = false;
    this.isSettingEndAngle = false;
  }


  createByPositions(positionsOrParams, callback) {
    if (!positionsOrParams) return;

    this.state = "startCreate";

    // 检查是否是扇环参数对象（包含center, innerRadius, outerRadius, startAngle, endAngle）
    if (positionsOrParams.center && positionsOrParams.innerRadius !== undefined && positionsOrParams.outerRadius !== undefined) {
      // 从参数对象创建扇环
      this.center = positionsOrParams.center;
      this.innerRadius = positionsOrParams.innerRadius;
      this.outerRadius = positionsOrParams.outerRadius;
      this.startAngle = Cesium.Math.toRadians(positionsOrParams.startAngle || 0);
      this.endAngle = Cesium.Math.toRadians(positionsOrParams.endAngle || 0);

      // 确保角度范围在0-2π之间
      if (this.endAngle < this.startAngle) {
        this.endAngle += Cesium.Math.TWO_PI;
      }

      // 计算控制点位置
      const innerStartPos = this.getPositionByAngleAndRadius(this.startAngle, this.innerRadius);
      const outerStartPos = this.getPositionByAngleAndRadius(this.startAngle, this.outerRadius);
      const outerEndPos = this.getPositionByAngleAndRadius(this.endAngle, this.outerRadius);

      // 创建控制点
      this.centerPoint = this.createPoint(this.center);
      this.centerPoint.typeAttr = "center";
      this.innerStartPoint = this.createPoint(innerStartPos);
      this.innerStartPoint.typeAttr = "innerStart";
      this.outerStartPoint = this.createPoint(outerStartPos);
      this.outerStartPoint.typeAttr = "outerStart";
      this.outerEndPoint = this.createPoint(outerEndPos);
      this.outerEndPoint.typeAttr = "outerEnd";

      // 隐藏控制点（编辑时再显示）
      if (this.centerPoint) this.centerPoint.show = false;
      if (this.innerStartPoint) this.innerStartPoint.show = false;
      if (this.outerStartPoint) this.outerStartPoint.show = false;
      if (this.outerEndPoint) this.outerEndPoint.show = false;

      this.entity = this.createSectorRingEntity();
      this.entity.objId = this.objId;
    } else {
      // 从坐标数组创建扇环
      let positions = [];
      if (Array.isArray(positionsOrParams)) {
        const isCartesian3 = positionsOrParams[0] instanceof Cesium.Cartesian3;
        if (isCartesian3) {
          positions = positionsOrParams;
        } else {
          positions = util.lnglatsToCartesians(positionsOrParams);
        }
      }

      if (!positions || positions.length < 5) {
        console.error('Invalid positions array for sector ring creation');
        return null;
      }

      // 解构参数
      const [center, innerRadius, outerRadius, startAngle, endAngle] = positions;

      // 检查中心点是否有效
      if (!center || this.hasNaNComponent(center)) {
        console.error('Invalid center point for sector ring creation');
        return null;
      }

      // 设置扇环参数
      this.center = center;
      this.innerRadius = innerRadius;
      this.outerRadius = outerRadius;
      // 将角度从度转换为弧度
      this.startAngle = Cesium.Math.toRadians(startAngle);
      this.endAngle = Cesium.Math.toRadians(endAngle);

      // 确保角度范围在0-2π之间
      if (this.endAngle < this.startAngle) {
        this.endAngle += Cesium.Math.TWO_PI;
      }

      // 计算控制点位置
      const innerStartPos = this.getPositionByAngleAndRadius(this.startAngle, this.innerRadius);
      const outerStartPos = this.getPositionByAngleAndRadius(this.startAngle, this.outerRadius);
      const outerEndPos = this.getPositionByAngleAndRadius(this.endAngle, this.outerRadius);

      // 创建控制点
      this.centerPoint = this.createPoint(this.center);
      this.centerPoint.typeAttr = "center";
      this.innerStartPoint = this.createPoint(innerStartPos);
      this.innerStartPoint.typeAttr = "innerStart";
      this.outerStartPoint = this.createPoint(outerStartPos);
      this.outerStartPoint.typeAttr = "outerStart";
      this.outerEndPoint = this.createPoint(outerEndPos);
      this.outerEndPoint.typeAttr = "outerEnd";

      // 隐藏控制点（编辑时再显示）
      if (this.centerPoint) this.centerPoint.show = false;
      if (this.innerStartPoint) this.innerStartPoint.show = false;
      if (this.outerStartPoint) this.outerStartPoint.show = false;
      if (this.outerEndPoint) this.outerEndPoint.show = false;

      this.entity = this.createSectorRingEntity();
    }

    this.state = "endCreate";
    // 启用扇环点击编辑功能
    this.enableClickToEdit();
    if (callback) callback(this.entity);
  }
};

/**
 * 结束标绘
 */


export default SectorRingDrawer;